<?php

namespace App\Observers;

use App\Models\Category;
use Illuminate\Support\Facades\DB;

class CategoryObserver
{
	public function saved(Category $category)
	{
		if ($category->transfer_id > 0
			and $category->transfer_id !== $category->id
			and Category::find($category->transfer_id)) {
			DB::transaction(function () use ($category) {
				$category->products()->update(['category_id' => $category->transfer_id]);
				$category->update(['transfer_id' => 0]);
			});
		}
		
		if ($category->is_show) {
			$category->addToCache();
		} else {
			$category->delFromCache();
		}
	}
	
    public function deleting(Category $category)
    {
    	if (has_child($category, 'children')) {
    		abort(403, '检测到关联子分类');
	    }
    	if (has_child($category, 'products')) {
    		abort(403, '检测到关联分类商品');
	    }
    }
    
    public function deleted(Category $category)
    {
    	$category->delFromCache();
    }
}
